﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ZX.Web.UI.Controls;
using ZX.KM.Service.ServiceProxy;
using ZX.KM.Service.Messages;
using ZX.KM.Core.Permission;
using ZX.KM.Core.Common;
using ZX.KM.Service.Contracts;

namespace ZX.WebApp.KM
{
    public class KmBasePage :BasePage
    {
        public RequestHeader CurrentRequestHeader
        {
            get
            {
                RequestHeader rh = new RequestHeader
                {
                    AccessToken = "字符串内容",
                    Action = "字符串内容",
                    ClientTag = "字符串内容",
                    RequestId = "字符串内容",
                    Version = "字符串内容",
                };
                return rh;
            }
        }

        /// <summary>
        /// 权限校验
        /// </summary>
        /// <param name="ResourceID">资源编号</param>
        /// <param name="PermissionString">权限常量，从PermissionConstants类中获取</param>
        /// <returns></returns>
        public bool CheckRight(Guid ResourceID, string PermissionString)
        {
            return HasPermission(this.UserId.Value, ResourceID, PermissionString);
        }

        static Dictionary<Guid, List<UserPositionInfo>> userPositions = new Dictionary<Guid, List<UserPositionInfo>>();
        Dictionary<Guid, GetOwnershipResourceListResponse> ownershipResourceListResponses = new Dictionary<Guid, GetOwnershipResourceListResponse>();
        /// <summary>
        /// 判断是否有权限信息
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返响应信息</returns>
        public bool HasPermission(Guid userID,Guid resourceID, string permissionString)
        {
            //取资源的权限信息
            IPermissionService target = ServiceProxyFactory.GetService<IPermissionService>();
            GetOwnershipResourceListResponse response;
            Guid resourceKey = resourceID;
            if (ownershipResourceListResponses.ContainsKey(resourceKey))
            {
                response = ownershipResourceListResponses[resourceKey];
            }
            else
            {
                GetOwnershipResourceListRequest req = new GetOwnershipResourceListRequest
                {
                    Body = new ZX.KM.Service.Criterias.GetOwnershipResourceListCriteria
                    {
                        ResourceID = resourceKey
                    }
                };

                response = target.GetOwnershipResourceList(req);
                ownershipResourceListResponses.Add(resourceKey, response);
            }

            //获取用户职位信息
            List<UserPositionInfo> userPositonList = new List<UserPositionInfo>();
            Guid userKey = userID;
            if (userPositions.ContainsKey(userKey))
            {
                userPositonList = userPositions[userKey];
            }
            else
            {
                Request<Guid> upRequest = new Request<Guid> { Body = userKey };
                Response<List<UserPositionInfo>> upResponse = target.GetUserPositionList(upRequest);
                if (upResponse != null && upResponse.Body != null)
                {
                    userPositions.Add(userKey, upResponse.Body);
                    userPositonList = upResponse.Body;
                }
            }


            bool hasRight = false;
            if (response != null)
            {
                //权限判断优先级(资源:文件柜->分类->文档,所有者:职务->组织结构->职位->用户)
                foreach (var r in response.Body.Result)
                {
                    if (r.IsOwner && r.OwnershipID == userID)
                    {
                        hasRight = true;
                        return hasRight;
                    }
                    foreach (UserPositionInfo up in userPositonList)
                    {
                        if (r.OwnershipID == up.UserID)
                        {
                            foreach (var p in r.Permissions)
                            {
                                if (p.PermissionName.Equals(permissionString))
                                {
                                    if (p.IsReject.HasValue)
                                    {
                                        hasRight = !p.IsReject.Value;
                                        return hasRight;
                                    }
                                    if (p.IsRejectForInherit.HasValue)
                                    {
                                        hasRight = !p.IsRejectForInherit.Value;
                                        return hasRight;
                                    }
                                }
                            }
                        }
                        else if (r.OwnershipID == up.PositionID)
                        {
                            foreach (var p in r.Permissions)
                            {
                                if (p.PermissionName.Equals(permissionString))
                                {
                                    if (p.IsReject.HasValue)
                                    {
                                        hasRight = !p.IsReject.Value;
                                        return hasRight;
                                    }
                                    if (p.IsRejectForInherit.HasValue)
                                    {
                                        hasRight = !p.IsRejectForInherit.Value;
                                        return hasRight;
                                    }
                                }
                            }
                        }
                        else if (r.OwnershipID == up.PostID)
                        {
                            foreach (var p in r.Permissions)
                            {
                                if (p.PermissionName.Equals(permissionString))
                                {
                                    if (p.IsReject.HasValue)
                                    {
                                        hasRight = !p.IsReject.Value;
                                        return hasRight;
                                    }
                                    if (p.IsRejectForInherit.HasValue)
                                    {
                                        hasRight = !p.IsRejectForInherit.Value;
                                        return hasRight;
                                    }
                                }
                            }
                        }
                        else if (r.OwnershipType == ZX.KM.Core.Enum.OwnerType.Organization
                            && up.DeptFullName.Contains(r.OwnershipName))
                        {
                            foreach (var p in r.Permissions)
                            {
                                if (p.PermissionName.Equals(permissionString))
                                {
                                    if (p.IsReject.HasValue)
                                    {
                                        hasRight = !p.IsReject.Value;
                                        return hasRight;
                                    }
                                    if (p.IsRejectForInherit.HasValue)
                                    {
                                        hasRight = !p.IsRejectForInherit.Value;
                                        return hasRight;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return hasRight;
        }

        /// <summary>
        /// 针对当前登录用户的权限[管理员拥有该权限]
        /// </summary>
        /// <param name="OwerID"></param>
        /// <returns></returns>
        public void PermissionForOwer(Guid OwerID)
        {
            bool hasPermission = false;
            if (OwerID == this.UserId) hasPermission = true;
            else hasPermission = false;
            Response.Clear();
            Response.ContentType = "application/json";
            Response.Write("{\"hasPermission\":\"" + hasPermission + "\"}");
        }

        /// <summary>
        /// 获取Request值
        /// </summary>
        public string QueryString(string key)
        {
            var str = string.Empty;
            if (Request[key] != null)
            {
                str = Request[key];
               // str = UrlEncoder.Encode(str);
            }
            return str;
        }

        /// <summary>
        /// 获取Request值
        /// </summary>
        public string QueryFormString(string key)
        {
            if (Request.Form[key] != null)
                return Request.Form[key];
            return string.Empty;
        }

        /// <summary>
        /// Json输出
        /// </summary>
        public void ResponseJson<T>(T t) where T : new()
        {
            string json = string.Empty;
            json = Utility.DataContractToJson(t);
            Response.Clear();
            Response.ContentType = "application/json";
            Response.Write(json);
            this.Page.Visible = false;
            Context.ApplicationInstance.CompleteRequest();
        }
    }

    public class ErrorModel
    {
        public string Code { get; set; }
        /// <summary>
        /// 当类型值为：-10001时，表示Ajax请求返回报错出错
        /// </summary>
        public string ErrorType { get; set; }
        public string ErrorMsg { get; set; }
    }
}